import pandas as pd
from enum import Enum
import json

def from_hdf5(key):
    config_path = Config.get_config_path()
    store = pd.HDFStore('{}/{}'.format(config_path, 'cache.h5'))
    df = None
    if '/' + key in store.keys():
        df = store.get(key=key)
    store.close()
    return df

def to_hdf5(key, df):
    config_path = Config.get_config_path()
    store = pd.HDFStore('{}/{}'.format(config_path, 'cache.h5'))
    store.put(key,df)
    store.close()

def class_2_dict(obj:object):
    dict = obj.__class__.__dict__
    dict_obj = obj.__dict__
    ret =  {}
    for k,v in dict_obj.items():
        if '__' not in k:
                ret[k] = v
    return ret



freq = Enum('freq',('每天','每周','运行一次'))
task_type = Enum('type',('传统量化','机器学习','强化学习'))
weight = Enum('weight',('等权','固定权重'))
orderby_dir = Enum('orderby',('DESC','ASC'))

PUBLIC_ENUMS = {
    'freq': freq,
    'type':task_type,
    'weight':weight,
    'orderby':orderby_dir
}

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) in PUBLIC_ENUMS.values():
            return {"__enum__": str(obj)}
        return json.JSONEncoder.default(self, obj)

def as_enum(d):
    if "__enum__" in d:
        name, member = d["__enum__"].split(".")
        return getattr(PUBLIC_ENUMS[name], member)
    else:
        return d